﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeamWork_Server.HTTP;
using System.IO;
using TeamWork_Server.Core;
using TeamWork_Server.Subscriptions;
using System.Threading;

namespace TeamWork_Server
{
    class Program
    {
        static string GetData(string p)
        {
            string[] ff = File.ReadAllLines(@".\config.ini");
            foreach (string f in ff)
            {
                if(f.Contains(p))
                    return f.Replace(p + "=", "").Replace('"', '\0').Trim('\0');
            }
            return "";
        }

        static bool CheckLastBeat(DateTime lBeat)
        {
            if (DateTime.Now.Subtract(lBeat).Seconds > 10)
            {
                return false;
            }
            return true;
        }

        static void Check()
        {
            while(true)
            {
                foreach (var v in User.Users)
                {
                    if(v.Value != null)
                    {
                        if (!CheckLastBeat(v.Value.LastHeartbeat))
                        {
                            if (v.Value.IsOnline)
                            {
                                v.Value.IsOnline = false;
                                Log.Info(v.Value.Name + " missed a heart-beat. Setting user status to offline.");
                            }
                        }
                    }
                }
                Thread.Sleep(10);
            }
        }

        static void Main(string[] args)
        {
            Log.Initialize("TeamWork Server.txt", LogLevel.All, false);
            Subscriptions:
            if (File.Exists(@".\subscriptions.dg"))
            {
                Subscriptions.Subscriptions.Initialize(@".\subscriptions.dg", false);
                Log.Info("Subscriptions file found! Initialized Subscriptions data grouper.");
            }
            else
            {
                Log.Info("Subscriptions file not found! Creating a new one and retyring...");
                Subscriptions.Subscriptions.Initialize(@".\subscriptions.dg");
                Log.Info("Subscription storage has been created. Press any key to continue...");
                Console.ReadKey();
                Console.Clear();
                goto Subscriptions;
            }
            CommandsFactory.Initialize();
            Console.Title = "TeamWork Server v0.2b";
            string ip = GetData("ServerExternalIP");
            CommandsFactory.Variables["net_external_ip"] = (ip=="localhost" ? "127.0.0.1" : ip);
            Log.Debug("Using IP: " + ip);
            long rp = long.Parse(GetData("RconPassword"));
            Log.Debug("Using RCON Password: " + rp.ToString());

            //Fill in the users data...
            Thread.Sleep(100);
            User u = new User();
            Log.Info("Parsing users, this may take a while...");
            DataObject[] users = User.Manager.Reader.GetObjects();
            if(users != null && users.Length > 1)
            {
                foreach (var user in users)
                {
                    if(user.ObjectValue != null && !User.Users.ContainsKey(int.Parse(user.ObjectName)))
                    {
                        MemoryStream memsr = new MemoryStream((byte[])user.ObjectValue);
                        BinaryReader reader = new BinaryReader(memsr);
                        string nick = reader.ReadString();
                        string pass = reader.ReadString();
                        string role = reader.ReadString();
                        int id = reader.ReadInt32();

                        User.Users.Add(id, new User(nick, pass, role, id));
                    }
                }
            }

            TWServerConfiguration c = new TWServerConfiguration(@GetData("StartupProject"));
            CommandsFactory.Variables["admin_master_key"] = long.Parse(c.MasterKey);
            RedirectService redirectService = new RedirectService(ip, c);
            redirectService.Start();
            RConHandler rch = new RConHandler(rp, c);
            rch.Start();
            SubscriptionService ss = new SubscriptionService();
            ss.Start();
            ChatService cs = new ChatService();
            cs.Start();
            Thread t = new Thread(Check);
            t.Start();
            while (true)
            {
                Log.WriteAway();
            }
        }
    }
}
